import { useSyncExternalStore } from 'react';

export const useStorage = (key: string, initValue: any) => {
    const subscribe = (callback: () => void) => {
        window.addEventListener('storage', callback);
        return () => {
            window.removeEventListener('storage', callback);
        };
    };
    const getSnapshot = () => {
        return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key))! : initValue;
    };
    const res = useSyncExternalStore(subscribe, getSnapshot);
    const updataStorage = (value: any) => {
        localStorage.setItem(key, JSON.stringify(value));
        window.dispatchEvent(new StorageEvent('storage'));
    };
    return [res, updataStorage];
};
